/**
 * @(#)TaskTimerServiceImpl.java 2018年1月6日
 * Copyright(C) 2018 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.timer;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.service.ITaskPoolService;
import org.jsbd.boss.service.impl.CacheParamManager;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service
public class TaskTimerServiceImpl implements TaskTimerService {
	public static final Logger LOGGER = LoggerFactory.getLogger(TaskTimerServiceImpl.class);

	@Resource
	private RedisClient<String, String> redisClient;

	@Resource
	private CacheParamManager cacheParamManager;

	@Resource
	private ITaskPoolService taskPoolService;

	/*
	 * (non-Javadoc)
	 *
	 * @see org.jsbd.boss.timer.TaskTimerService#execute()
	 */
	@Override
	public void execute() {
		try {
			long expireTime = 60;
			Map<String, TaskAdapterHandler> map = SpringContextUtils.getBeansOfType(TaskAdapterHandler.class);
			Collection<TaskAdapterHandler> serviceList = map.values();
			int i = 0;
			Iterator<TaskAdapterHandler> iterator = serviceList.iterator();
			Object refreshTime = cacheParamManager.getParamValue(CacheKey.TASK_TIMER_TIME);
			if (refreshTime != null) {
				expireTime = Long.parseLong(refreshTime.toString());
			}
			while (iterator.hasNext()) {
				TaskAdapterHandler service = iterator.next();
				if (redisClient.evalSetNx(CacheKey.TASK_TIMER_LOCK + i, expireTime)) {
					try {
						LOGGER.info("task handler {} timer  {}", i, service.getClass().getSimpleName());
						taskPoolService.execTaskTimer(service);
					} catch (Exception e) {
						LOGGER.error("task handler {} timer ", i, e);
					}
				}
				i++;
			}
		} catch (Exception e) {
			LOGGER.error("TaskTimerServiceImpl error", e);
		}

	}

}
